package com.example.controller;

import com.example.entity.Student;
import com.example.entity.User;
import com.example.service.StudentService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ResponseBody
    public List<Student> getAllStudents(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            return studentService.findAll();
        } else if (user.getRole().equals("TEACHER")) {
            // 教师只能查看自己管理的班级的学生
            return studentService.findByClass(user.getUsername());
        } else {
            // 学生只能查看自己的信息
            return Collections.singletonList(studentService.findByStudentId(user.getUsername()));
        }
    }

    @GetMapping("/{id}")
    @ResponseBody
    public Student getStudentById(@PathVariable String id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN") ||
                (user.getRole().equals("TEACHER") && studentService.findByClass(user.getUsername()).stream()
                        .anyMatch(s -> s.getStudentId().equals(id))) ||
                (user.getRole().equals("STUDENT") && user.getUsername().equals(id))) {
            return studentService.findByStudentId(id);
        }
        return null;
    }

    @PostMapping
    @ResponseBody
    public Map<String, Object> addStudent(@RequestBody Student student, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            try {
                studentService.addStudent(student);
                User newUser = new User();
                newUser.setUsername(student.getStudentId());
                newUser.setPassword("123456");
                newUser.setRole("STUDENT");
                userService.addUser(newUser);
                result.put("success", true);
                result.put("message", "添加成功");
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "添加失败：" + e.getMessage());
            }
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @PutMapping
    @ResponseBody
    public Map<String, Object> updateStudent(@RequestBody Student student, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN") ||
                (user.getRole().equals("TEACHER") && studentService.findByClass(user.getUsername()).stream()
                        .anyMatch(s -> s.getStudentId().equals(student.getStudentId()))) ||
                (user.getRole().equals("STUDENT") && user.getUsername().equals(student.getStudentId()))) {
            try {
                studentService.updateStudent(student);
                result.put("success", true);
                result.put("message", "更新成功");
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "更新失败：" + e.getMessage());
            }
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public Map<String, Object> deleteStudent(@PathVariable String id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user.getRole().equals("ADMIN")) {
            try {
                Student student = studentService.findByStudentId(id);
                if (student != null) {
                    User newUser = userService.findByUsername(student.getStudentId());
                    userService.deleteUser(newUser.getId());
                    studentService.deleteStudent(student.getStudentId());
                    result.put("success", true);
                    result.put("message", "删除成功");
                } else {
                    result.put("success", false);
                    result.put("message", "学生不存在");
                }
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "删除失败：" + e.getMessage());
            }
        } else {
            result.put("success", false);
            result.put("message", "权限不足");
        }
        return result;
    }

    // 获取当前登录学生的信息
    @GetMapping("/info")
    public ResponseEntity<?> getStudentInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.badRequest().body("未登录");
        }

        Student student = studentService.findByStudentId(user.getUsername());
        if (student == null) {
            return ResponseEntity.badRequest().body("学生信息不存在");
        }

        return ResponseEntity.ok(student);
    }

    // 更新学生信息
    @PutMapping("/update")
    public ResponseEntity<?> updateStudentInfo(@RequestBody Student student, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.badRequest().body("未登录");
        }

        Student existingStudent = studentService.findByStudentId(user.getUsername());
        if (existingStudent == null) {
            return ResponseEntity.badRequest().body("学生信息不存在");
        }

        // 只允许更新特定字段
        existingStudent.setChineseName(student.getChineseName());
        existingStudent.setEnglishName(student.getEnglishName());
        existingStudent.setTel(student.getTel());

        try {
            studentService.updateStudent(existingStudent);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    // 更新密码
    @PostMapping("/update-password")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, String> passwords, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.badRequest().body("未登录");
        }

        String oldPassword = passwords.get("oldPassword");
        String newPassword = passwords.get("newPassword");

        if (oldPassword == null || newPassword == null) {
            return ResponseEntity.badRequest().body("参数不完整");
        }

        try {
            userService.updatePassword(user.getUsername(), oldPassword, newPassword);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "密码修改成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "密码修改失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
} 